'use client';

import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import { evaluateOrder } from '@/service/actions/order';
import { useState, useTransition } from 'react';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';

const array = [0, 1, 2, 3, 4];

export default function EvaluateOrder({
  orderId,
  evaluation,
}: {
  orderId: number;
  evaluation: {
    deliver: number;
    product: number;
  };
}) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [deliverRate, setDeliverRate] = useState(evaluation.deliver);
  const [productRate, setProductRate] = useState(evaluation.product);
  const [open, setOpen] = useState(false);

  const onSubmit = async () => {
    startTransition(async () => {
      const { error } = await evaluateOrder({
        orderId,
        deliverRate,
        productRate,
      });
      error
        ? toast({ title: error.message, variant: 'destructive' })
        : toast({ title: '订单评价成功' });
      !error && setOpen(false);
    });
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline">评价订单</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader className="space-y-4">
          <DialogTitle>评价订单</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <div className="w-fit mx-auto space-y-3">
          <div className="flex items-center gap-2">
            商品评分:
            {array.map((k, i) => (
              <span
                onClick={() => setProductRate(i + 1)}
                className={cn(
                  'text-xl hover:cursor-pointer',
                  i < productRate ? 'i-ri-star-fill' : 'i-ri-star-line',
                )}
                key={k}
              />
            ))}
          </div>
          <div className="flex items-center gap-2">
            配送评分:
            {array.map((k, i) => (
              <span
                onClick={() => setDeliverRate(i + 1)}
                className={cn(
                  'text-xl hover:cursor-pointer',
                  i < deliverRate ? 'i-ri-star-fill' : 'i-ri-star-line',
                )}
                key={k}
              />
            ))}
          </div>
        </div>
        <div className="flex justify-end gap-5">
          <Button
            variant="outline"
            onClick={() => {
              setOpen(false);
              setDeliverRate(evaluation.deliver);
              setProductRate(evaluation.product);
            }}
          >
            取消
          </Button>
          <Button disabled={isPending} onClick={onSubmit}>
            {isPending && <span className="i-ri-loader-4-fill animate-spin" />}
            确认
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
